// API基础URL
const API_BASE_URL = '/api';

// DOM元素（将在DOMContentLoaded中初始化）
let goodsTableBody, inboundTableBody, outboundTableBody, totalGoodsEl, inboundCountEl, outboundCountEl;
let loginSection, mainContent, loginForm, logoutBtn;
let addGoodsModal, addGoodsForm, editGoodsModal, editGoodsForm, addInboundModal, addInboundForm, addOutboundModal, addOutboundForm, closeModalBtns;
let importGoodsBtn, exportGoodsBtn, fileInput;
let tabButtons, tabPanes;
let addGoodsBtn, addInboundBtn, addOutboundBtn;
// 新增查看单据详情模态框元素
let viewInboundModal, viewOutboundModal, inboundDetailContent, outboundDetailContent;

// JWT令牌
let authToken = localStorage.getItem('authToken');

// 当前编辑的货物信息
let currentEditGoods = null;

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM加载完成，开始初始化...');
    
    // 初始化DOM元素
    initializeDOMElements();
    
    // 检查关键DOM元素是否存在
    console.log('关键DOM元素检查:');
    console.log('addInboundBtn:', addInboundBtn);
    console.log('addOutboundBtn:', addOutboundBtn);
    console.log('addInboundModal:', addInboundModal);
    console.log('addOutboundModal:', addOutboundModal);
    
    // 检查用户是否已登录
    if (authToken) {
        showMainContent();
        loadAllData();
    } else {
        showLoginSection();
    }
    
    // 绑定事件监听器
    bindEventListeners();
});

// 初始化DOM元素
function initializeDOMElements() {
    // 表格元素
    goodsTableBody = document.querySelector('#goodsTable tbody');
    inboundTableBody = document.querySelector('#inboundTable tbody');
    outboundTableBody = document.querySelector('#outboundTable tbody');
    totalGoodsEl = document.getElementById('totalGoods');
    inboundCountEl = document.getElementById('inboundCount');
    outboundCountEl = document.getElementById('outboundCount');

    // 认证相关元素
    loginSection = document.getElementById('loginSection');
    mainContent = document.getElementById('mainContent');
    loginForm = document.getElementById('loginForm');
    logoutBtn = document.getElementById('logoutBtn');

    // 模态框元素
    addGoodsModal = document.getElementById('addGoodsModal');
    addGoodsForm = document.getElementById('addGoodsForm');
    editGoodsModal = document.getElementById('editGoodsModal');
    editGoodsForm = document.getElementById('editGoodsForm');
    addInboundModal = document.getElementById('addInboundModal');
    addInboundForm = document.getElementById('addInboundForm');
    addOutboundModal = document.getElementById('addOutboundModal');
    addOutboundForm = document.getElementById('addOutboundForm');
    closeModalBtns = document.querySelectorAll('.close');
    
    // 查看单据详情模态框元素
    viewInboundModal = document.getElementById('viewInboundModal');
    viewOutboundModal = document.getElementById('viewOutboundModal');
    inboundDetailContent = document.getElementById('inboundDetailContent');
    outboundDetailContent = document.getElementById('outboundDetailContent');

    // 数据导入/导出元素
    importGoodsBtn = document.getElementById('importGoodsBtn');
    exportGoodsBtn = document.getElementById('exportGoodsBtn');
    fileInput = document.getElementById('fileInput');

    // Tab元素
    tabButtons = document.querySelectorAll('.tab-btn');
    tabPanes = document.querySelectorAll('.tab-pane');

    // 按钮元素
    addGoodsBtn = document.getElementById('addGoodsBtn');
    addInboundBtn = document.getElementById('addInboundBtn');
    addOutboundBtn = document.getElementById('addOutboundBtn');
}

// 绑定事件监听器
function bindEventListeners() {
    console.log('开始绑定事件监听器...');
    
    // 登录表单提交
    if (loginForm) {
        loginForm.addEventListener('submit', handleLogin);
        console.log('已绑定登录表单提交事件');
    }
    
    // 登出按钮
    if (logoutBtn) {
        logoutBtn.addEventListener('click', handleLogout);
        console.log('已绑定登出按钮点击事件');
    }
    
    // Tab切换
    tabButtons.forEach(button => {
        button.addEventListener('click', switchTab);
    });
    console.log('已绑定Tab切换事件');
    
    // 添加货物按钮
    if (addGoodsBtn) {
        addGoodsBtn.addEventListener('click', openAddGoodsModal);
        console.log('已绑定添加货物按钮点击事件');
    }
    
    // 创建入库单据按钮
    if (addInboundBtn) {
        addInboundBtn.addEventListener('click', openAddInboundModal);
        console.log('已绑定创建入库单据按钮点击事件');
    } else {
        console.error('入库单据按钮未找到');
    }
    
    // 创建出库单据按钮
    if (addOutboundBtn) {
        addOutboundBtn.addEventListener('click', openAddOutboundModal);
        console.log('已绑定创建出库单据按钮点击事件');
    } else {
        console.error('出库单据按钮未找到');
    }
    
    // 关闭模态框按钮
    if (closeModalBtns) {
        closeModalBtns.forEach(btn => {
            btn.addEventListener('click', closeAllModals);
        });
        console.log('已绑定关闭模态框按钮点击事件');
    }
    
    // 点击模态框外部关闭
    window.addEventListener('click', function(event) {
        if (event.target === addGoodsModal || 
            event.target === editGoodsModal || 
            event.target === addInboundModal || 
            event.target === addOutboundModal ||
            event.target === viewInboundModal ||
            event.target === viewOutboundModal) {
            closeAllModals();
        }
    });
    
    // 添加货物表单提交
    if (addGoodsForm) {
        addGoodsForm.addEventListener('submit', handleAddGoodsSubmit);
    }
    
    // 编辑货物表单提交
    if (editGoodsForm) {
        editGoodsForm.addEventListener('submit', handleEditGoodsSubmit);
    }
    
    // 创建入库单据表单提交
    if (addInboundForm) {
        addInboundForm.addEventListener('submit', handleAddInboundSubmit);
    }
    
    // 创建出库单据表单提交
    if (addOutboundForm) {
        addOutboundForm.addEventListener('submit', handleAddOutboundSubmit);
    }
    
    // 数据导入/导出
    if (importGoodsBtn) {
        importGoodsBtn.addEventListener('click', triggerFileSelect);
    }
    
    if (fileInput) {
        fileInput.addEventListener('change', handleFileUpload);
    }
    
    if (exportGoodsBtn) {
        exportGoodsBtn.addEventListener('click', exportGoodsData);
    }
    
    console.log('事件监听器绑定完成');
}

// 显示登录界面
function showLoginSection() {
    console.log('显示登录界面');
    if (loginSection) loginSection.style.display = 'block';
    if (mainContent) mainContent.style.display = 'none';
}

// 显示主内容界面
function showMainContent() {
    console.log('显示主内容界面');
    if (loginSection) loginSection.style.display = 'none';
    if (mainContent) mainContent.style.display = 'block';
}

// 处理登录
function handleLogin(event) {
    event.preventDefault();
    
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    
    fetch(`${API_BASE_URL}/auth/login`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            authToken = data.data.token;
            localStorage.setItem('authToken', authToken);
            showMainContent();
            loadAllData();
        } else {
            alert('登录失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('登录失败:', error);
        alert('登录失败');
    });
}

// 处理登出
function handleLogout() {
    authToken = null;
    localStorage.removeItem('authToken');
    showLoginSection();
}

// 切换Tab
function switchTab(event) {
    console.log('切换Tab:', event.target);
    const tabName = event.target.getAttribute('data-tab');
    
    // 更新激活的tab按钮
    tabButtons.forEach(btn => btn.classList.remove('active'));
    event.target.classList.add('active');
    
    // 显示对应的tab内容
    tabPanes.forEach(pane => pane.classList.remove('active'));
    const targetPane = document.getElementById(tabName);
    if (targetPane) {
        targetPane.classList.add('active');
    }
}

// 打开添加货物模态框
function openAddGoodsModal() {
    console.log('打开添加货物模态框');
    if (addGoodsModal) {
        // 清空表单
        if (addGoodsForm) addGoodsForm.reset();
        addGoodsModal.style.display = 'block';
    }
}

// 打开编辑货物模态框
function openEditGoodsModal(goods) {
    console.log('打开编辑货物模态框:', goods);
    if (editGoodsModal) {
        // 填充表单数据
        document.getElementById('editGoodsId').value = goods.id;
        document.getElementById('editGoodsName').value = goods.name;
        document.getElementById('editGoodsSku').value = goods.sku;
        document.getElementById('editGoodsQuantity').value = goods.quantity;
        document.getElementById('editGoodsLocation').value = goods.location || '';
        document.getElementById('editGoodsStatus').value = goods.status;
        document.getElementById('editGoodsBatch').value = goods.batch_number || '';
        
        currentEditGoods = goods;
        editGoodsModal.style.display = 'block';
    }
}

// 打开创建入库单据模态框
function openAddInboundModal() {
    console.log('打开创建入库单据模态框');
    if (addInboundModal) {
        // 设置默认日期为今天
        const today = new Date().toISOString().split('T')[0];
        const expectedDateEl = document.getElementById('inboundExpectedDate');
        if (expectedDateEl) {
            expectedDateEl.value = today;
        }
        
        // 清空表单
        if (addInboundForm) addInboundForm.reset();
        if (expectedDateEl) {
            expectedDateEl.value = today;
        }
        
        addInboundModal.style.display = 'block';
    } else {
        console.error('入库单据模态框元素未找到');
    }
}

// 打开创建出库单据模态框
function openAddOutboundModal() {
    console.log('打开创建出库单据模态框');
    if (addOutboundModal) {
        // 设置默认日期为今天
        const today = new Date().toISOString().split('T')[0];
        const expectedDateEl = document.getElementById('outboundExpectedDate');
        if (expectedDateEl) {
            expectedDateEl.value = today;
        }
        
        // 清空表单
        if (addOutboundForm) addOutboundForm.reset();
        if (expectedDateEl) {
            expectedDateEl.value = today;
        }
        
        addOutboundModal.style.display = 'block';
    } else {
        console.error('出库单据模态框元素未找到');
    }
}

// 关闭所有模态框
function closeAllModals() {
    console.log('关闭所有模态框');
    if (addGoodsModal) addGoodsModal.style.display = 'none';
    if (editGoodsModal) editGoodsModal.style.display = 'none';
    if (addInboundModal) addInboundModal.style.display = 'none';
    if (addOutboundModal) addOutboundModal.style.display = 'none';
    if (viewInboundModal) viewInboundModal.style.display = 'none';
    if (viewOutboundModal) viewOutboundModal.style.display = 'none';
    
    // 重置表单
    if (addGoodsForm) addGoodsForm.reset();
    if (editGoodsForm) editGoodsForm.reset();
    if (addInboundForm) addInboundForm.reset();
    if (addOutboundForm) addOutboundForm.reset();
}

// 处理添加货物表单提交
function handleAddGoodsSubmit(event) {
    event.preventDefault();
    
    const goodsData = {
        name: document.getElementById('goodsName').value,
        sku: document.getElementById('goodsSku').value,
        quantity: parseInt(document.getElementById('goodsQuantity').value) || 0,
        location: document.getElementById('goodsLocation').value,
        status: document.getElementById('goodsStatus').value,
        batchNumber: document.getElementById('goodsBatch').value
    };
    
    createGoods(goodsData);
}

// 处理编辑货物表单提交
function handleEditGoodsSubmit(event) {
    event.preventDefault();
    
    const id = document.getElementById('editGoodsId').value;
    const goodsData = {
        name: document.getElementById('editGoodsName').value,
        sku: document.getElementById('editGoodsSku').value,
        quantity: parseInt(document.getElementById('editGoodsQuantity').value) || 0,
        location: document.getElementById('editGoodsLocation').value,
        status: document.getElementById('editGoodsStatus').value,
        batchNumber: document.getElementById('editGoodsBatch').value
    };
    
    updateGoods(id, goodsData);
}

// 处理创建入库单据表单提交
function handleAddInboundSubmit(event) {
    event.preventDefault();
    
    const inboundData = {
        goodsId: parseInt(document.getElementById('inboundGoodsId').value),
        supplier: document.getElementById('inboundSupplier').value,
        quantity: parseInt(document.getElementById('inboundQuantity').value) || 1,
        expectedArrivalDate: document.getElementById('inboundExpectedDate').value,
        operator: document.getElementById('inboundOperator').value,
        notes: document.getElementById('inboundNotes').value
    };
    
    createInboundDocument(inboundData);
}

// 处理创建出库单据表单提交
function handleAddOutboundSubmit(event) {
    event.preventDefault();
    
    const outboundData = {
        goodsId: parseInt(document.getElementById('outboundGoodsId').value),
        customer: document.getElementById('outboundCustomer').value,
        quantity: parseInt(document.getElementById('outboundQuantity').value) || 1,
        expectedPickupDate: document.getElementById('outboundExpectedDate').value,
        operator: document.getElementById('outboundOperator').value,
        notes: document.getElementById('outboundNotes').value
    };
    
    createOutboundDocument(outboundData);
}

// 加载所有数据
function loadAllData() {
    loadGoods();
    loadInboundDocuments();
    loadOutboundDocuments();
}

// 加载货物数据
function loadGoods() {
    if (!authToken) return;
    
    fetch(`${API_BASE_URL}/goods`, {
        headers: {
            'Authorization': `Bearer ${authToken}`
        }
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderGoodsTable(data.data);
                if (totalGoodsEl) totalGoodsEl.textContent = data.data.length;
            }
        })
        .catch(error => {
            console.error('加载货物数据失败:', error);
        });
}

// 渲染货物表格
function renderGoodsTable(goodsList) {
    if (!goodsTableBody) return;
    
    goodsTableBody.innerHTML = '';
    
    goodsList.forEach(goods => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${goods.id}</td>
            <td>${goods.name}</td>
            <td>${goods.sku}</td>
            <td>${goods.quantity}</td>
            <td>${goods.location || '-'}</td>
            <td>${getStatusText(goods.status)}</td>
            <td>
                <button class="btn-primary" onclick='openEditGoodsModal(${JSON.stringify(goods).replace(/'/g, "\\'")})'>编辑</button>
                <button class="btn-primary" onclick="deleteGoods(${goods.id})">删除</button>
            </td>
        `;
        goodsTableBody.appendChild(row);
    });
}

// 获取状态文本
function getStatusText(status) {
    const statusMap = {
        'inStock': '在库',
        'outStock': '出库',
        'reserved': '预留'
    };
    return statusMap[status] || status;
}

// 创建货物
function createGoods(goodsData) {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    fetch(`${API_BASE_URL}/goods`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${authToken}`
        },
        body: JSON.stringify(goodsData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('货物创建成功');
            closeAllModals();
            loadGoods();
        } else {
            alert('货物创建失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('创建货物失败:', error);
        alert('创建货物失败');
    });
}

// 更新货物
function updateGoods(id, goodsData) {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    fetch(`${API_BASE_URL}/goods/${id}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${authToken}`
        },
        body: JSON.stringify(goodsData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('货物更新成功');
            closeAllModals();
            loadGoods();
        } else {
            alert('货物更新失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('更新货物失败:', error);
        alert('更新货物失败');
    });
}

// 删除货物
function deleteGoods(id) {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    if (confirm('确定要删除这个货物吗？')) {
        fetch(`${API_BASE_URL}/goods/${id}`, {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('货物删除成功');
                loadGoods();
            } else {
                alert('货物删除失败: ' + data.message);
            }
        })
        .catch(error => {
            console.error('删除货物失败:', error);
            alert('删除货物失败');
        });
    }
}

// 创建入库单据
function createInboundDocument(inboundData) {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    console.log('创建入库单据数据:', inboundData);
    
    fetch(`${API_BASE_URL}/inbound`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${authToken}`
        },
        body: JSON.stringify(inboundData)
    })
    .then(response => response.json())
    .then(data => {
        console.log('入库单据创建响应:', data);
        if (data.success) {
            alert('入库单据创建成功');
            closeAllModals();
            loadInboundDocuments();
        } else {
            alert('入库单据创建失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('创建入库单据失败:', error);
        alert('创建入库单据失败');
    });
}

// 创建出库单据
function createOutboundDocument(outboundData) {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    console.log('创建出库单据数据:', outboundData);
    
    fetch(`${API_BASE_URL}/outbound`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${authToken}`
        },
        body: JSON.stringify(outboundData)
    })
    .then(response => response.json())
    .then(data => {
        console.log('出库单据创建响应:', data);
        if (data.success) {
            alert('出库单据创建成功');
            closeAllModals();
            loadOutboundDocuments();
        } else {
            alert('出库单据创建失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('创建出库单据失败:', error);
        alert('创建出库单据失败');
    });
}

// 加载入库单据数据
function loadInboundDocuments() {
    if (!authToken) return;
    
    fetch(`${API_BASE_URL}/inbound`, {
        headers: {
            'Authorization': `Bearer ${authToken}`
        }
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderInboundTable(data.data);
                if (inboundCountEl) inboundCountEl.textContent = data.data.length;
            }
        })
        .catch(error => {
            console.error('加载入库单据数据失败:', error);
        });
}

// 渲染入库单据表格
function renderInboundTable(documents) {
    if (!inboundTableBody) return;
    
    inboundTableBody.innerHTML = '';
    
    documents.forEach(doc => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${doc.id}</td>
            <td>${doc.goods_id}</td>
            <td>${doc.supplier}</td>
            <td>${doc.quantity}</td>
            <td>${formatDate(doc.expected_arrival_date)}</td>
            <td>${getDocumentStatusText(doc.status)}</td>
            <td>
                <button class="btn-primary" onclick="viewInboundDocument(${doc.id})">查看</button>
                <button class="btn-primary" onclick="updateInboundStatus(${doc.id}, 'received')">接收</button>
                <button class="btn-primary" onclick="updateInboundStatus(${doc.id}, 'completed')">完成</button>
            </td>
        `;
        inboundTableBody.appendChild(row);
    });
}

// 加载出库单据数据
function loadOutboundDocuments() {
    if (!authToken) return;
    
    fetch(`${API_BASE_URL}/outbound`, {
        headers: {
            'Authorization': `Bearer ${authToken}`
        }
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderOutboundTable(data.data);
                if (outboundCountEl) outboundCountEl.textContent = data.data.length;
            }
        })
        .catch(error => {
            console.error('加载出库单据数据失败:', error);
        });
}

// 渲染出库单据表格
function renderOutboundTable(documents) {
    if (!outboundTableBody) return;
    
    outboundTableBody.innerHTML = '';
    
    documents.forEach(doc => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${doc.id}</td>
            <td>${doc.goods_id}</td>
            <td>${doc.customer}</td>
            <td>${doc.quantity}</td>
            <td>${formatDate(doc.expected_pickup_date)}</td>
            <td>${getDocumentStatusText(doc.status)}</td>
            <td>
                <button class="btn-primary" onclick="viewOutboundDocument(${doc.id})">查看</button>
                <button class="btn-primary" onclick="updateOutboundStatus(${doc.id}, 'picked')">拣货</button>
                <button class="btn-primary" onclick="updateOutboundStatus(${doc.id}, 'completed')">完成</button>
            </td>
        `;
        outboundTableBody.appendChild(row);
    });
}

// 获取单据状态文本
function getDocumentStatusText(status) {
    const statusMap = {
        'pending': '待处理',
        'received': '已接收',
        'picked': '已拣货',
        'shipped': '已发货',
        'completed': '已完成',
        'cancelled': '已取消'
    };
    return statusMap[status] || status;
}

// 格式化日期
function formatDate(dateString) {
    if (!dateString) return '-';
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN');
}

// 查看入库单据详情
function viewInboundDocument(id) {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    console.log('查看入库单据详情，ID:', id);
    
    fetch(`${API_BASE_URL}/inbound/${id}`, {
        headers: {
            'Authorization': `Bearer ${authToken}`
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            renderInboundDetail(data.data);
            if (viewInboundModal) {
                viewInboundModal.style.display = 'block';
            }
        } else {
            alert('获取入库单据详情失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('获取入库单据详情失败:', error);
        alert('获取入库单据详情失败');
    });
}

// 渲染入库单据详情
function renderInboundDetail(document) {
    if (!inboundDetailContent) return;
    
    const detailHTML = `
        <div class="document-detail">
            <div class="detail-row">
                <span class="detail-label">单据ID:</span>
                <span class="detail-value">${document.id}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">货物ID:</span>
                <span class="detail-value">${document.goods_id}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">供应商:</span>
                <span class="detail-value">${document.supplier}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">数量:</span>
                <span class="detail-value">${document.quantity}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">预计到达日期:</span>
                <span class="detail-value">${formatDate(document.expected_arrival_date)}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">实际到达日期:</span>
                <span class="detail-value">${document.actual_arrival_date ? formatDate(document.actual_arrival_date) : '-'}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">状态:</span>
                <span class="detail-value">${getDocumentStatusText(document.status)}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">操作员:</span>
                <span class="detail-value">${document.operator || '-'}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">备注:</span>
                <span class="detail-value">${document.notes || '-'}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">创建时间:</span>
                <span class="detail-value">${formatDate(document.created_at)}</span>
            </div>
            ${document.status === 'cancelled' ? `
            <div class="detail-row">
                <span class="detail-label">取消原因:</span>
                <span class="detail-value">${document.cancellation_reason || '-'}</span>
            </div>
            ` : ''}
        </div>
    `;
    
    inboundDetailContent.innerHTML = detailHTML;
}

// 查看出库单据详情
function viewOutboundDocument(id) {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    console.log('查看出库单据详情，ID:', id);
    
    fetch(`${API_BASE_URL}/outbound/${id}`, {
        headers: {
            'Authorization': `Bearer ${authToken}`
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            renderOutboundDetail(data.data);
            if (viewOutboundModal) {
                viewOutboundModal.style.display = 'block';
            }
        } else {
            alert('获取出库单据详情失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('获取出库单据详情失败:', error);
        alert('获取出库单据详情失败');
    });
}

// 渲染出库单据详情
function renderOutboundDetail(document) {
    if (!outboundDetailContent) return;
    
    const detailHTML = `
        <div class="document-detail">
            <div class="detail-row">
                <span class="detail-label">单据ID:</span>
                <span class="detail-value">${document.id}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">货物ID:</span>
                <span class="detail-value">${document.goods_id}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">客户:</span>
                <span class="detail-value">${document.customer}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">数量:</span>
                <span class="detail-value">${document.quantity}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">预计提货日期:</span>
                <span class="detail-value">${formatDate(document.expected_pickup_date)}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">实际提货日期:</span>
                <span class="detail-value">${document.actual_pickup_date ? formatDate(document.actual_pickup_date) : '-'}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">状态:</span>
                <span class="detail-value">${getDocumentStatusText(document.status)}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">操作员:</span>
                <span class="detail-value">${document.operator || '-'}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">备注:</span>
                <span class="detail-value">${document.notes || '-'}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">创建时间:</span>
                <span class="detail-value">${formatDate(document.created_at)}</span>
            </div>
            ${document.status === 'cancelled' ? `
            <div class="detail-row">
                <span class="detail-label">取消原因:</span>
                <span class="detail-value">${document.cancellation_reason || '-'}</span>
            </div>
            ` : ''}
        </div>
    `;
    
    outboundDetailContent.innerHTML = detailHTML;
}

// 更新入库单据状态
function updateInboundStatus(id, status) {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    fetch(`${API_BASE_URL}/inbound/${id}/status`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${authToken}`
        },
        body: JSON.stringify({ status })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('入库单据状态更新成功');
            loadInboundDocuments();
        } else {
            alert('状态更新失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('更新入库单据状态失败:', error);
        alert('状态更新失败');
    });
}

// 更新出库单据状态
function updateOutboundStatus(id, status) {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    fetch(`${API_BASE_URL}/outbound/${id}/status`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${authToken}`
        },
        body: JSON.stringify({ status })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('出库单据状态更新成功');
            loadOutboundDocuments();
        } else {
            alert('状态更新失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('更新出库单据状态失败:', error);
        alert('状态更新失败');
    });
}

// 触发文件选择
function triggerFileSelect() {
    if (fileInput) fileInput.click();
}

// 处理文件上传
function handleFileUpload(event) {
    const file = event.target.files[0];
    if (!file) return;
    
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    const formData = new FormData();
    formData.append('file', file);
    
    fetch(`${API_BASE_URL}/data/import/goods/csv`, {
        method: 'POST',
        headers: {
            'Authorization': `Bearer ${authToken}`
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('数据导入成功: ' + data.message);
            loadGoods();
        } else {
            alert('数据导入失败: ' + data.message);
        }
        // 清空文件输入
        if (fileInput) fileInput.value = '';
    })
    .catch(error => {
        console.error('数据导入失败:', error);
        alert('数据导入失败');
        // 清空文件输入
        if (fileInput) fileInput.value = '';
    });
}

// 导出货物数据
function exportGoodsData() {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    window.open(`${API_BASE_URL}/data/export/goods/csv`, '_blank');
}